﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace UtilLib.Misc
{
	/// <summary>
	/// 一种通用的将byte数组流转换为对象的方法
	/// </summary>
	/// <see cref="http://www.cnblogs.com/TianFang/archive/2012/10/06/2712987.html"/>
	static class MarshalObject
	{
		public static byte[] ObjectToBytes<T>(T obj)
		{
			int len = Marshal.SizeOf(obj);
			byte[] arr = new byte[len];

			IntPtr ptr = Marshal.AllocHGlobal(len);
			Marshal.StructureToPtr(obj, ptr, true);
			Marshal.Copy(ptr, arr, 0, len);
			Marshal.FreeHGlobal(ptr);

			return arr;
		}

		public static T BytesToObject<T>(byte[] bytearray)
		{
			int len = Marshal.SizeOf(typeof(T));

			IntPtr i = Marshal.AllocHGlobal(len);
			Marshal.Copy(bytearray, 0, i, len);
			var output = Marshal.PtrToStructure(i, typeof(T));
			Marshal.FreeHGlobal(i);

			return (T)output;
		}
	}
}
